package svc

import (
	_ "github.com/go-sql-driver/mysql"
	"group-card/common/tool"
	"group-card/model/entity"
	"group-card/model/sysmodel"
	"group-card/rpc/sys/internal/config"
	"time"
	"xorm.io/core"
	"xorm.io/xorm"
)

type ServiceContext struct {
	Config        config.Config
	CustomerModel sysmodel.SysCustomerModel
}

func NewServiceContext(c config.Config) *ServiceContext {

	//sqlConn := sqlx.NewMysql(c.Mysql.Datasource) // 连接数据库
	Orm, err := xorm.NewEngine(c.Mysql.DriverName, c.Mysql.Datasource)
	if err != nil {
		tool.GLogLine("mysql数据库连接失败", err)
	}
	//连接测试
	if err := Orm.Ping(); err != nil {
		tool.GLogLine("mysql数据库连接失败", err)
	}
	//日志打印SQL
	Orm.ShowSQL(true)
	//设置连接池的空闲数大小
	Orm.SetMaxIdleConns(100)
	//设置最大打开连接数
	Orm.SetMaxOpenConns(500)
	//名称映射规则主要负责结构体名称到表名和结构体field到表字段的名称映射
	Orm.SetTableMapper(core.SnakeMapper{})
	Orm.TZLocation, _ = time.LoadLocation("Asia/Shanghai")
	//连接成功
	tool.GLogLine("mysql数据库连接成功")

	err = Orm.Sync2(
		new(entity.SysCustomer),
	)
	if err != nil {
		tool.GLogLine("生成表失败:", err)
	}

	return &ServiceContext{
		Config:        c,
		CustomerModel: sysmodel.NewSysCustomerModel(Orm),
	}
}
